package com.TanNgee.remoting.transport.netty.client;

import com.TanNgee.remoting.dto.RpcResponse;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用于存放未被服务端处理的请求
 * 利用CompletableFuture来异步获取Netty请求的响应结果，将每个请求对应的CompletableFuture实例都保存在一个Map中，
 * key为请求ID，value为创建的CompletableFuture实例
 */
public class UnprocessedRequests {

    private static final Map<String, CompletableFuture<RpcResponse<Object>>> UNPROCESSED_RESPONSE_FUTURES = new ConcurrentHashMap<>();

    public void put(String requestId, CompletableFuture<RpcResponse<Object>> future) {
        UNPROCESSED_RESPONSE_FUTURES.put(requestId, future);
    }

    public void complete(RpcResponse<Object> rpcResponse) {
        //请求完成了，把请求从未完成的请求中移除
        CompletableFuture<RpcResponse<Object>> future = UNPROCESSED_RESPONSE_FUTURES.remove(rpcResponse.getRequestId());

        if (null != future) {
            //把响应对象放入future中
            future.complete(rpcResponse);
        } else {
            throw new IllegalStateException();
        }
    }
}